const Koa=require('koa');
const Router=require('koa-router');
const bodyParser=require('koa-bodyparser');
const static=require('koa-static');
const app=new Koa();
const router=new Router();
const {query}=require('./db');
const jwt=require('jsonwebtoken');
const key='shen';
const port=3000;

app.use(bodyParser());

//注册
router.post('/register',async ctx=>{
    let {userName,password}=ctx.request.body;
    const data=await query(`select * from goods where userName = '${userName}'`);
    if(data.length>0){
        ctx.body={message:'已存在'};
    }else{
        await query(`insert into goods (userName,password) values ('${userName}','${password}')`);
        // const token=jwt.sign({userName},key,{expiresIn: '1h'});
        ctx.body={message:'不存在'};
    }
})

//登录
router.post('/login',async ctx=>{
    let {userName,password}=ctx.request.body;
    const data=await query(`select userName from goods where userName = '${userName}' and password = '${password}'`);
    if(data.length>0){
        ctx.body={message:'登录成功',data};
    }else{
        ctx.body={message:'登录失败'};
    }
})

app.use(static(__dirname + '/views'));

app.use(router.routes());

app.listen(port,()=>console.log(`服务器已启动:http://localhost:${port}`));